package com.john.myokhttpimagerecycledemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.john.myokhttpimagerecycledemo.adapter.MAdapter;

import com.john.myokhttpimagerecycledemo.bean.IBean;
import com.john.myokhttpimagerecycledemo.constant.URLString;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    @Bind(R.id.recycleView)
    RecyclerView mRecycleView;

    private List<IBean.ListBean> mDatas;
    private MAdapter mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mDatas=new ArrayList<>();
//        LayoutInflater.from(this).inflate(R.layout.item_activity, null);
        downLoad();
        mAdapter = new MAdapter(this,mDatas);
        mRecycleView.setAdapter(mAdapter);
        mRecycleView.setLayoutManager(new LinearLayoutManager(this));
    }

    private void downLoad() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(URLString.E_URL)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String result = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        IBean iBean = new Gson().fromJson(result, IBean.class);
                        mDatas.addAll(iBean.result.list);
                        mAdapter.notifyDataSetChanged();
                    }
                });
            }
        });
    }
}
